# -*- coding: utf-8 -*-
# @Time   : 2024-04-26 16:35
# @Author : 大龙 🚀
import math

import scrapy
import re
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider
from utils.tools import urlencode


class HainanHnslyhwhgdtyt4475Policy(BaseTaxPolicySpider):
    name = 'hainan_hnslyhwhgdtyt_4475_policy'

    province = "海南省"
    city = ""
    county = ""
    park = ""
    source = "海南省旅游和文化广电体育厅"

    def start_requests(self):
        page_url = 'https://lwt.hainan.gov.cn/xxgk_55333/0200/0202/newxxgk2020.html?ClassInfoId=2009'
        url = 'https://lwt.hainan.gov.cn/xxgk_55333/0200/0202/1893/2009/list.html'
        yield scrapy.Request(url, callback=self.parse_list)

    def parse_list(self, response, **kwargs):
        prev_item = response.meta.get('item')
        is_json = response.meta.get('is_json')
        if is_json is None:
            for elem in response.xpath('//tr/td[@class="name"]/a'):
                item = Item()
                item['source_url'] = elem.xpath("""./@href""").re_first(r"""(.*)""")
                item['source_url'] = response.urljoin(item['source_url'])
                item['publish_date'] = elem.xpath("""string(.)""").get()
                if prev_item is not None:
                    for key, value in prev_item.items():
                        item[key] = value
                if not item['source_url']:
                    continue
                yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        else:
            for info in response.json()['object']['xxgk']:
                item = Item()
                item['source_url'] = info['DOCPUBURL']
                item['publish_date'] = info['PUBDATE'][:10]
                if prev_item is not None:
                    for key, value in prev_item.items():
                        item[key] = value
                if not item['source_url']:
                    continue
                yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        if response.meta.get("is_next") is not False:
            total = response.xpath("""//script""").re_first(r"""m_nRecordCount = "(\d+)";""")
            total_page = math.ceil(int(total) / 20)
            for page_num in range(1, int(total_page)):
                if page_num < 9:
                    url = f'https://lwt.hainan.gov.cn/xxgk_55333/0200/0202/1893/2009/list_{page_num}.html'
                    yield response.follow(url, callback=self.parse_list, meta={'item': prev_item, 'is_next': False})
                else:
                    url = "https://lwt.hainan.gov.cn/hnsearch/xxgk/"
                    data = {
                        "classinfoid": "2009",
                        "channelid": "74828",
                        "pagesize": "20",
                        "currpage": f"{page_num + 1}"
                    }
                    yield scrapy.FormRequest(url, callback=self.parse_list, formdata=data,
                                             meta={'item': prev_item, 'is_next': False, 'is_json': True})

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").get()
        item['content'] = response.xpath(""".""").get()
        item['province'] = self.province
        item['city'] = self.city
        item['county'] = self.county
        item['park'] = self.park
        item['source'] = self.source
        yield item


if __name__ == "__main__":
    from scrapy import cmdline
    cmdline.execute("scrapy crawl hainan_hnslyhwhgdtyt_4475_policy".split())
